<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-left">
        <div class="welcome-content">
          <router-link to="/" class="logo">
            <img src="@/assets/images/logo.png" alt="瓜子二手车">
            <span>瓜子二手车</span>
          </router-link>
          <h1>欢迎回来</h1>
          <p>二手车直卖网，没有中间商赚差价</p>
          <div class="features">
            <div class="feature-item">
              <el-icon><Lock /></el-icon>
              <span>259项专业检测</span>
            </div>
            <div class="feature-item">
              <el-icon><TrendCharts /></el-icon>
              <span>没有中间商赚差价</span>
            </div>
            <div class="feature-item">
              <el-icon><Medal /></el-icon>
              <span>1年2万公里质保</span>
            </div>
          </div>
        </div>
      </div>

      <div class="login-right">
        <div class="login-form-container">
          <div class="form-header">
            <h2>{{ isLogin ? '登录账号' : '注册账号' }}</h2>
            <p>{{ isLogin ? '欢迎回到瓜子二手车' : '创建您的瓜子二手车账号' }}</p>
          </div>
          <!-- 手机号重复提示 -->
          <div v-if="showDuplicatePhoneAlert" class="duplicate-phone-alert">
            <div class="alert-content">
              <span class="alert-text">该手机号已注册，请直接登录</span>
              <el-link 
                type="primary" 
                class="login-link"
                @click="switchToLogin"
              >
                去登录
              </el-link>
            </div>
          </div>
          <div v-if="showPasswordErrorAlert" class="password-error-alert">
            <div class="alert-content">
              <span class="alert-text">用户名或密码错误，请重试</span>
            </div>
          </div>
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            class="login-form"
            @keyup.enter="handleSubmit"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                size="large"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="formData.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item v-if="!isLogin" prop="confirmPassword">
              <el-input
                v-model="formData.confirmPassword"
                type="password"
                placeholder="请确认密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item v-if="!isLogin" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入姓名"
                size="large"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-btn"
                :loading="loading"
                @click="handleSubmit"
              >
                {{ isLogin ? '登录' : '注册' }}
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <div class="mode-switch">
              <span>{{ isLogin ? '还没有账号？' : '已有账号？' }}</span>
              <el-button type="text" @click="toggleMode">
                {{ isLogin ? '立即注册' : '立即登录' }}
              </el-button>
            </div>

            <div class="divider">
              <span>或</span>
            </div>

            <div class="social-login">
              <el-button class="social-btn wechat">
                <el-icon><ChatDotRound /></el-icon>
                微信登录
              </el-button>
              <el-button class="social-btn qq">
                <el-icon><Iphone /></el-icon>
                QQ登录
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  User, 
  Lock, 
  TrendCharts, 
  Medal, 
  ChatDotRound, 
  Iphone 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const isLogin = ref(true)
const loading = ref(false)
const formRef = ref()
const phoneInputRef = ref()
const passwordInputRef = ref()
const showDuplicatePhoneAlert = ref(false)
const showPasswordErrorAlert = ref(false)

const formData = reactive({
  phone: '',
  password: '',
  confirmPassword: '',
  name: ''
})

const formRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!isLogin.value && value !== formData.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ]
}

const toggleMode = () => {
  isLogin.value = !isLogin.value
  showDuplicatePhoneAlert.value = false
  showPasswordErrorAlert.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 切换到登录模式并填充手机号
const switchToLogin = () => {
  isLogin.value = true
  showDuplicatePhoneAlert.value = false
  showPasswordErrorAlert.value = false
  // 保留手机号，清空其他字段
  const currentPhone = formData.phone
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.phone = currentPhone
  formData.password = ''
  formData.confirmPassword = ''
  formData.name = ''
}

// 处理密码错误的情况
const handlePasswordError = () => {
  showPasswordErrorAlert.value = true
  // 清空密码字段
  formData.password = ''
  // 等待DOM更新后聚焦到密码输入框
  nextTick(() => {
    if (passwordInputRef.value) {
      passwordInputRef.value.focus()
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    showDuplicatePhoneAlert.value = false
    showPasswordErrorAlert.value = false

    if (isLogin.value) {
      // 登录逻辑
      await userStore.loginUser({
        phone: formData.phone,
        password: formData.password
      })
      ElMessage.success('登录成功')
      
      // 跳转到目标页面或首页
      const redirect = route.query.redirect || '/'
      router.push(redirect)
    } else {
      // 注册逻辑
      await userStore.registerUser({
        phone: formData.phone,
        password: formData.password,
        name: formData.name
      })
      ElMessage.success('注册成功')
      
      // 注册成功后自动登录
      await userStore.loginUser({
        phone: formData.phone,
        password: formData.password
      })
      
      // 跳转到目标页面或首页
      const redirect = route.query.redirect || '/'
      router.push(redirect)
    }
  } catch (error) {
    console.error('表单提交错误:', error)
    
    // 更详细的错误信息检查
    const errorMessage = error.message || ''
    const responseData = error.response?.data || {}
    const status = error.response?.status
    
    console.log('错误详情:', {
      errorMessage,
      responseData,
      status,
      fullError: error
    })
    
    if (isLogin.value) {
      // 登录时的错误处理
      const hasPasswordError = 
        errorMessage.includes('密码错误') || 
        errorMessage.includes('密码不正确') ||
        errorMessage.includes('用户名或密码错误') ||
        (responseData.message && (
          responseData.message.includes('密码错误') ||
          responseData.message.includes('密码不正确') ||
          responseData.message.includes('用户名或密码错误')
        )) ||
        (responseData.error && (
          responseData.error.includes('密码错误') ||
          responseData.error.includes('密码不正确') ||
          responseData.error.includes('用户名或密码错误')
        )) ||
        // 如果后端返回401状态码（未授权），通常表示密码错误
        status === 401
      
      if (hasPasswordError) {
        // 处理密码错误
        handlePasswordError()
      } else {
        // 其他登录错误
        const errorMsg = responseData.message || responseData.error || '登录失败'
        ElMessage.error(errorMsg)
      }
    } else {
      // 注册时的错误处理
      const hasDuplicatePhoneError = 
        errorMessage.includes('手机号已注册') || 
        errorMessage.includes('手机号已被注册') ||
        errorMessage.includes('该手机号已注册') ||
        (responseData.message && (
          responseData.message.includes('手机号已注册') ||
          responseData.message.includes('手机号已被注册') ||
          responseData.message.includes('该手机号已注册')
        )) ||
        (responseData.error && (
          responseData.error.includes('手机号已注册') ||
          responseData.error.includes('手机号已被注册') ||
          responseData.error.includes('该手机号已注册')
        )) ||
        // 如果后端返回400状态码且没有明确错误信息，我们也认为是手机号重复
        (status === 400 && !isLogin.value)
      
      if (hasDuplicatePhoneError) {
        // 显示橙色提示框
        showDuplicatePhoneAlert.value = true
        console.log('检测到手机号重复错误，显示提示框')
      } else {
        // 其他注册错误
        const errorMsg = responseData.message || responseData.error || '注册失败'
        ElMessage.error(errorMsg)
      }
    }
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff6a00 0%, #ff8c00 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1000px;
  width: 100%;
  overflow: hidden;
}

.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff6a00 0%, #ff8c00 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1000px;
  width: 100%;
  overflow: hidden;
}

.login-left {
  background: linear-gradient(135deg, #ff6a00 0%, #ff8c00 100%);
  color: white;
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;

  .welcome-content {
    text-align: center;

    .logo {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 40px;
      text-decoration: none;
      color: white;
      font-size: 24px;
      font-weight: bold;

      img {
        height: 32px;
      }
    }

    h1 {
      margin: 0 0 16px;
      font-size: 32px;
      font-weight: 600;
    }

    p {
      margin: 0 0 40px;
      font-size: 16px;
      opacity: 0.9;
    }

    .features {
      display: flex;
      flex-direction: column;
      gap: 20px;

      .feature-item {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 16px;

        .el-icon {
          font-size: 20px;
        }
      }
    }
  }
}

.login-right {
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form-container {
  width: 100%;
  max-width: 360px;

  .form-header {
    text-align: center;
    margin-bottom: 40px;

    h2 {
      margin: 0 0 8px;
      font-size: 28px;
      color: #333;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }
}

.login-form {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  :deep(.el-input) {
    .el-input__wrapper {
      padding: 12px 16px;
      border-radius: 8px;

      &.is-focus {
        box-shadow: 0 0 0 2px rgba(255, 106, 0, 0.2);
      }
    }
  }

  .login-btn {
    width: 100%;
    border-radius: 8px;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
  }
}

.form-footer {
  margin-top: 30px;

  .mode-switch {
    text-align: center;
    margin-bottom: 20px;

    span {
      color: #666;
      font-size: 14px;
    }

    .el-button {
      font-size: 14px;
      color: #ff6a00;
    }
  }

  .divider {
    position: relative;
    text-align: center;
    margin: 20px 0;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 1px;
      background: #f0f0f0;
    }

    span {
      background: white;
      padding: 0 16px;
      color: #999;
      font-size: 12px;
      position: relative;
    }
  }

  .social-login {
    display: flex;
    gap: 12px;

    .social-btn {
      flex: 1;
      border-radius: 8px;
      padding: 12px;
      border: 1px solid #f0f0f0;

      &.wechat:hover {
        border-color: #07C160;
        color: #07C160;
      }

      &.qq:hover {
        border-color: #12B7F5;
        color: #12B7F5;
      }
    }
  }
}

@media (max-width: 768px) {
  .login-container {
    grid-template-columns: 1fr;
  }

  .login-left {
    display: none;
  }

  .login-right {
    padding: 40px 20px;
  }

  .social-login {
    flex-direction: column;
  }
}
</style>